package 书店销售管理系统;

import java.awt.*;
import java.awt.event.*;
import java.sql.*;

import javax.swing.*;
import javax.swing.table.*;

public class Book extends JFrame {
    private static final long serialVersionUID = 1L;
    private JTable table;
    private DefaultTableModel model;

    private final String url = "jdbc:oracle:thin:@localhost:1521:xe";
    private final String user = "HR";
    private final String password = "123456";

    public Book() {
        setTitle("图书信息管理");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(900, 700);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());

        // 设置背景
        JPanel background = new JPanel() {
            /**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
            protected void paintComponent(Graphics g) {
                super.paintComponent(g);
                // 绘制半透明粉色背景
                g.setColor(new Color(255, 192, 203, 128));
                g.fillRect(0, 0, getWidth(), getHeight());
            }
        };
        add(background, BorderLayout.CENTER);

        // 创建顶部面板
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        topPanel.setOpaque(false); // 设置为透明背景
        
        // 创建菜单栏
        JMenuBar menuBar = new JMenuBar();
        setJMenuBar(menuBar);

        // 添加下拉菜单
        JMenu dropDownMenu = new JMenu("菜单");
        menuBar.add(dropDownMenu);

        // 添加子菜单：销售信息管理
        JMenuItem salesItem = new JMenuItem("销售信息管理");
        salesItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“销售信息管理”界面的代码
            	new SalesManagement().setVisible(true);
            }
        });
        dropDownMenu.add(salesItem);

        // 添加子菜单：会员信息管理
        JMenuItem memberItem = new JMenuItem("会员信息管理");
        memberItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员信息管理”界面的代码
            	new MemberManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem);
         
        // 添加子菜单：会员类别管理
        JMenuItem memberItem1 = new JMenuItem("会员类别管理");
        memberItem1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员类别管理”界面的代码
            	new VipTypeManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem1);
        
        // 添加子菜单：会员类别管理
        JMenuItem memberItem11 = new JMenuItem("用户信息管理");
        memberItem11.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 在此添加跳转到“会员类别管理”界面的代码
            	new UserManagement().setVisible(true);
            }
        });
        dropDownMenu.add(memberItem11);
        
        
        // 添加子菜单：退出
        JMenuItem exitItem = new JMenuItem("退出");
        exitItem.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                dispose(); // 关闭窗口
                System.exit(0); // 退出应用程序
            }
        });
        dropDownMenu.add(exitItem);

        // 添加按钮：添加、编辑、删除、查询
        JButton addButton = new JButton("Add");
        addButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                BookDialog dialog = new BookDialog(Book.this, "Add Book", null);
                if (dialog.isOK()) {
                    addBook(dialog.getData());
                }
            }
        });
        topPanel.add(addButton);

        JButton editButton = new JButton("Edit");
        editButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                if (row >= 0) {
                    String id = (String) model.getValueAt(row, 0);
                    Object[] data = { id, model.getValueAt(row, 1), model.getValueAt(row, 2), model.getValueAt(row, 3),
                            model.getValueAt(row, 4), model.getValueAt(row, 5), model.getValueAt(row, 6) };
                    BookDialog dialog = new BookDialog(Book.this, "Edit Book", data);
                    if (dialog.isOK()) {
                        editBook(dialog.getData());
                    }
                } else {
                    JOptionPane.showMessageDialog(Book.this, "Please select a book to edit.");
                }
            }
        });
        topPanel.add(editButton);

        JButton deleteButton = new JButton("Delete");
        deleteButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                int row = table.getSelectedRow();
                System.out.println(row);
                if (row >= 0) {
                    String id = (String) model.getValueAt(row, 0);
                    int result = JOptionPane.showConfirmDialog(Book.this,
                            "Are you sure you want to delete book \"" + model.getValueAt(row, 1) + "\"?",
                            "Delete Book", JOptionPane.YES_NO_OPTION);
                    if (result == JOptionPane.YES_OPTION) {
                        deleteBook(id);
                    }
                } else {
                    JOptionPane.showMessageDialog(Book.this, "Please select a book to delete.");
                }
            }
        });
        topPanel.add(deleteButton);

        JTextField searchField = new JTextField(20);
        searchField.setHorizontalAlignment(JTextField.CENTER); // 设置文本框居中对齐
        searchField.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchBook(searchField.getText());
            }
        });
        topPanel.add(searchField);

        JButton searchButton = new JButton("Search");
        searchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                searchBook(searchField.getText());
            }
        });
        topPanel.add(searchButton);

        // 添加顶部面板
        background.add(topPanel, BorderLayout.NORTH);

        // 创建表格
        String[] columnNames = { "图书编号", "图书名", "作者", "价格", "图书类型", "出版社", "库存" };
        model = new DefaultTableModel(columnNames, 0);
        table = new JTable(model) {
            private static final long serialVersionUID = 1L;

            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        JScrollPane scrollPane = new JScrollPane(table);
        table.setPreferredScrollableViewportSize(new Dimension(800, 500));

        scrollPane.setOpaque(false);
        scrollPane.getViewport().setOpaque(false);
        background.add(scrollPane, BorderLayout.CENTER);

        refreshTable(); // 刷新表格
        setVisible(true);
    }

    private void refreshTable() {
        model.setRowCount(0); // 清空表格数据
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery("SELECT * FROM BOOK");
            while (rs.next()) {
                String id = rs.getString("BNO");
                String name = rs.getString("BNAME");
                String author = rs.getString("AUTHOR");
                Float price = rs.getFloat("PRICE");
                String category = rs.getString("BTYPE");
                String publisher = rs.getString("BPRESS");
                Integer stock = rs.getInt("INVENTORY");
                model.addRow(new Object[] { id, name, author, price, category, publisher, stock });
            }
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void addBook(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement(
                    "INSERT INTO BOOK (BNO, BNAME, AUTHOR, PRICE, BTYPE, BPRESS, INVENTORY) VALUES (?, ?, ?, ?, ?, ?, ?)");
            pstmt.setString(1, data[0].toString());
            pstmt.setString(2, data[1].toString());
            pstmt.setString(3, data[2].toString());
            pstmt.setFloat(4, Float.parseFloat(data[3].toString()));
            pstmt.setString(5, data[4].toString());
            pstmt.setString(6, data[5].toString());
            pstmt.setInt(7, Integer.parseInt(data[6].toString()));
            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 添加成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void editBook(Object[] data) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement(
                    "UPDATE BOOK SET BNAME = ?, AUTHOR = ?, PRICE = ?, BTYPE = ?, BPRESS = ?, INVENTORY = ? WHERE BNO = ?");
            pstmt.setString(1, data[1].toString());
            pstmt.setString(2, data[2].toString());
            pstmt.setFloat (3, Float.parseFloat(data[3].toString()));
            pstmt.setString(4, data[4].toString());
            pstmt.setString(5, data[5].toString());
            pstmt.setInt(6, Integer.parseInt(data[6].toString()));
            pstmt.setString(7, data[0].toString());

            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 修改成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void deleteBook(String id) {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            PreparedStatement pstmt = conn.prepareStatement("DELETE FROM BOOK WHERE BNO = ?");
            pstmt.setString(1, id);
            pstmt.executeUpdate();
            conn.close();
            refreshTable(); // 删除成功后刷新表格
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private void searchBook(String keyword) {
        model.setRowCount(0); // 清空表格数据
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection conn = DriverManager.getConnection(url, user, password);
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(
                    "SELECT * FROM BOOK WHERE UPPER(BNAME) LIKE '%" + keyword.toUpperCase() + "%' OR UPPER(AUTHOR) LIKE '%"
                            + keyword.toUpperCase() + "%' OR UPPER(BPRESS) LIKE '%" + keyword.toUpperCase() + "%'OR UPPER(BNO) LIKE '%"
                            +keyword.toUpperCase()+"%' OR UPPER(BTYPE) LIKE '%" + keyword.toUpperCase() +"%'");
            while (rs.next()) {
                String id = rs.getString("BNO");
                String name = rs.getString("BNAME");
                String author = rs.getString("AUTHOR");
                Float price = rs.getFloat("PRICE");
                String category = rs.getString("BTYPE");
                String publisher = rs.getString("BPRESS");
                Integer stock = rs.getInt("INVENTORY");
                model.addRow(new Object[] { id, name, author, price, category, publisher, stock });
            }
            conn.close();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    private class BookDialog extends JDialog {
        private static final long serialVersionUID = 1L;
        private JTextField idField = new JTextField(10);
        private JTextField nameField = new JTextField(10);
        private JTextField authorField = new JTextField(10);
        private JTextField priceField = new JTextField(10);
        private JTextField categoryField = new JTextField(10);
        private JTextField publisherField = new JTextField(10);
        private JTextField stockField = new JTextField(10);
        private boolean isOK = false;

        public BookDialog(JFrame parent, String title, Object[] initData) {
            super(parent, title, true);
            setLocationRelativeTo(parent);
            setLayout(new GridLayout(0, 2, 10, 5));

            add(idField); 
            add(new JLabel("图书编号:"));
            add(idField); 
            add(new JLabel("图书名:"));
            add(nameField); 
            add(new JLabel("作者:"));
            add(authorField); 
            add(new JLabel("价格:")); 
            add(priceField); 
            add(new JLabel("图书类型:")); 
            add(categoryField); 
            add(new JLabel("出版社:")); 
            add(publisherField); 
            add(new JLabel("库存:")); 
            add(stockField);

            // 初始化数据
            if (initData != null) {
                idField.setText(initData[0].toString());
                nameField.setText(initData[1].toString());
                authorField.setText(initData[2].toString());
                priceField.setText(initData[3].toString());
                categoryField.setText(initData[4].toString());
                publisherField.setText(initData[5].toString());
                stockField.setText(initData[6].toString());
            }

            // 添加按钮：确定、取消
            JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
            JButton okButton = new JButton("OK");
            okButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    isOK = true;
                    dispose();
                }
            });
            buttonPanel.add(okButton);

            JButton cancelButton = new JButton("Cancel");
            cancelButton.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    isOK = false;
                    dispose();
                }
            });
            buttonPanel.add(cancelButton);

            add(buttonPanel);

            pack();
            setVisible(true);
        }

        public boolean isOK() {
            return isOK;
        }

        public Object[] getData() {
            Object[] data = { idField.getText(), nameField.getText(), authorField.getText(), priceField.getText(),
                    categoryField.getText(), publisherField.getText(), stockField.getText() };
            return data;
        }
    }

    public static void main(String[] args) {
        new Book();
    }
    }